package cn.lj.payment.controller.controller;

import cn.lj.payment.config.AliPayProperties;
import cn.lj.payment.mapper.pojo.SmallMiGoodsOrder;
import cn.lj.payment.service.service.PayMentService;
import com.alibaba.nacos.common.model.RestResult;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description: OrderController
 * @author: lijie
 * @date: 2021年07月26日 上午 09:54:45
 */
@RestController
@RequestMapping("ali")
public class PayMentController {
    @Autowired
    private AliPayProperties aliPayProperties;
    @Autowired
    private PayMentService payMentService;
    /**
     * 功能描述: 支付宝支付接口
     * @auther: lijie
     * @param response:
     * @date: 2021/7/26 下午 05:52:25
     * @return: void
     */
    @GetMapping("/alipay")
    public void alipay(SmallMiGoodsOrder smallMiGoodsOrder, HttpServletResponse response) throws AlipayApiException, IOException {
        payMentService.alipay(smallMiGoodsOrder,response);
    }
    /**
     * 功能描述: 支付宝支付后回调
     * @auther: lijie
     * @param request:
     * @date: 2021/7/26 下午 03:38:54
     * @return: com.alibaba.nacos.common.model.RestResult<java.lang.Void>
     */
    @PostMapping("/getreturn")
    public RestResult<Void> getreturn(HttpServletRequest request) throws AlipayApiException {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //去支付宝查自己的配置如果都通过返回true，然后我们再做判断
        boolean b = AlipaySignature.rsaCertCheckV1(params, aliPayProperties.getCertPath(), aliPayProperties.getCharset(), aliPayProperties.getSignType());
        if (b){
            payMentService.checkNotifyurl(params);
        }
        return new RestResult<>();
    }
}
